<template>
  <div class="organization-container">
    <div class="page-header">
      <h1 class="page-title">机构管理</h1>
      <p class="page-description">管理医疗机构信息</p>
    </div>

    <div class="content-area">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="机构名称">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入机构名称"
              clearable
              size="default"
              style="width: 180px; height: 32px"
            />
          </el-form-item>
          <el-form-item label="省市区域">
            <el-cascader
              v-model="searchForm.regionCascader"
              :options="regionOptions"
              :props="cascaderProps"
              placeholder="请选择省份/城市"
              clearable
              size="default"
              style="width: 200px; height: 32px"
              @change="handleSearchRegionChange"
            />
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable size="default" style="width: 160px; height: 32px">
              <el-option 
                v-for="category in categoryOptions" 
                :key="category" 
                :label="category" 
                :value="category" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable size="default" style="width: 160px; height: 32px">
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" size="default" style="height: 32px; padding: 0 16px">搜索</el-button>
            <el-button @click="handleReset" size="default" style="height: 32px; padding: 0 16px">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-section">
        <div class="action-left">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增机构
          </el-button>
          <el-button 
            type="success" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchEnable"
          >
            <el-icon><Check /></el-icon>
            批量启用 ({{ selectedRows.length }})
          </el-button>
          <el-button 
            type="warning" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchDisable"
          >
            <el-icon><Close /></el-icon>
            批量禁用 ({{ selectedRows.length }})
          </el-button>
          <el-button 
            type="danger" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除 ({{ selectedRows.length }})
          </el-button>
        </div>
        <div class="action-right">
          <el-select 
            v-model="sortConfig.field" 
            placeholder="排序字段" 
            style="width: 120px; margin-right: 8px"
            @change="handleSortChange"
          >
            <el-option label="创建时间" value="createTime" />
            <el-option label="评分" value="rating" />
            <el-option label="浏览量" value="viewCount" />
          </el-select>
          <el-select 
            v-model="sortConfig.order" 
            placeholder="排序方式" 
            style="width: 100px"
            @change="handleSortChange"
          >
            <el-option label="降序" value="desc" />
            <el-option label="升序" value="asc" />
          </el-select>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table 
          :data="tableData" 
          :loading="loading"
          border
          stripe
          height="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="机构图片" width="100">
            <template #default="scope">
              <el-image 
                v-if="scope.row.image && scope.row.image.trim()"
                :src="scope.row.image"
                style="width: 50px; height: 50px;"
                fit="cover"
                :preview-src-list="[scope.row.image]"
                :preview-teleported="true"
              >
                <template #error>
                  <div style="display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; background-color: #f5f7fa; color: #909399; font-size: 12px;">
                    无图片
                  </div>
                </template>
              </el-image>
              <div v-else style="display: flex; align-items: center; justify-content: center; width: 50px; height: 50px; background-color: #f5f7fa; color: #909399; font-size: 12px;">
                无图片
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="机构名称" />
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="category" label="分类" />
          <el-table-column label="浏览量" width="100" align="center">
            <template #default="scope">
              <span style="color: #409EFF; font-weight: 500;">
                {{ scope.row.viewCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="评分" width="150">
            <template #default="scope">
              <RatingDisplay :value="scope.row.rating" />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                {{ scope.row.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑机构弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑机构' : '新增机构'"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form 
        ref="organizationFormRef" 
        :model="organizationForm" 
        :rules="organizationRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构名称" prop="name">
              <el-input v-model="organizationForm.name" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构分类" prop="category">
              <el-select v-model="organizationForm.category" placeholder="请选择分类" style="width: 100%">
                <el-option 
                  v-for="category in categoryOptions" 
                  :key="category" 
                  :label="category" 
                  :value="category" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机构状态">
              <el-select v-model="organizationForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="active" />
                <el-option label="禁用" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="省市区域" prop="regionCascader">
              <el-cascader
                v-model="organizationForm.regionCascader"
                :options="regionOptions"
                :props="cascaderProps"
                placeholder="请选择省份/城市"
                style="width: 100%"
                @change="handleRegionChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="详细地址" prop="location">
              <el-input v-model="organizationForm.location" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>




        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="机构标签">
              <el-input 
                v-model="organizationForm.tag" 
                placeholder="请输入机构标签（如：石家庄市吸脂人气热销榜第1名）" 
                type="textarea"
                :rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="机构Logo" prop="logo">
              <!-- 没有图片时显示上传组件 -->
              <el-upload
                v-if="logoFileList.length === 0"
                :http-request="uploadRequest"
                name="file"
                list-type="picture-card"
                :limit="1"
                :on-exceed="handleUploadExceed"
                :before-upload="beforeUpload"
                :headers="uploadHeaders"
                accept="image/*"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    只能上传一张图片，支持 jpg/png/gif 格式，大小不超过 2MB
                  </div>
                </template>
              </el-upload>
              
              <!-- 有图片时只显示图片和操作按钮 -->
              <div v-else class="uploaded-logo-container">
                <div class="logo-preview">
                  <el-image
                    :src="logoFileList[0]?.url"
                    fit="cover"
                    class="logo-image"
                    @click="handlePreview(logoFileList[0])"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                        <span>加载失败</span>
                      </div>
                    </template>
                  </el-image>
                  <div class="logo-actions">
                    <el-button 
                      size="small" 
                      type="primary" 
                      @click="handlePreview(logoFileList[0])"
                      circle
                    >
                      <el-icon><ZoomIn /></el-icon>
                    </el-button>
                    <el-button 
                      size="small" 
                      type="danger" 
                      @click="handleUploadRemove"
                      circle
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 图片预览查看器 -->
      <el-image-viewer
        v-if="previewDialogVisible"
        :url-list="[previewImageUrl]"
        :initial-index="0"
        @close="previewDialogVisible = false"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElImageViewer } from 'element-plus'
import { Plus, Delete, Picture, ZoomIn, Check, Close } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { provinceAndCityData } from 'element-china-area-data'
import RatingDisplay from '@/views/datalist/Component/rating/RatingDisplay.vue'

// 定义接口类型
interface Organization {
  id: string  // 修改为string类型，因为MongoDB的ObjectId是字符串
  image?: string
  name: string
  address: string
  category?: string
  rating?: number
  status: 'active' | 'inactive'
  createTime: string
  province?: string
  city?: string
  tag?: string
  location?: string
}

interface SearchForm {
  name: string
  status: string
  province: string
  city: string
  category: string
  regionCascader: string[]
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Organization[]>([])
const selectedRows = ref<Organization[]>([]) // 选中的行数据

const searchForm = reactive<SearchForm>({
  name: '',
  status: '',
  province: '',
  city: '',
  category: '',
  regionCascader: []
})

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 排序配置
const sortConfig = reactive({
  field: 'createTime',
  order: 'desc'
})

// 省份选项
const provinceOptions = ref(provinceAndCityData)

// 搜索区域级联选择器变化处理
const handleSearchRegionChange = (value: string | string[]) => {
  if (!value || (Array.isArray(value) && value.length === 0)) {
    searchForm.city = ''
    searchForm.province = ''
    return
  }

  try {
    // 处理数组格式的值（完整路径）
    if (Array.isArray(value) && value.length >= 2) {
      const [provinceValue, cityValue] = value
      
      // 根据省份和城市代码找到对应的名称
      for (const province of regionOptions.value) {
        if (province.value === provinceValue && province.children) {
          searchForm.province = province.label
          for (const city of province.children) {
            if (city.value === cityValue) {
              searchForm.city = city.label
              return
            }
          }
        }
      }
    }
    // 处理只选择省份的情况
    else if (Array.isArray(value) && value.length === 1) {
      const [provinceValue] = value
      for (const province of regionOptions.value) {
        if (province.value === provinceValue) {
          searchForm.province = province.label
          searchForm.city = '' // 清空城市
          return
        }
      }
    }
    // 处理单个值格式（向后兼容）
    else if (typeof value === 'string') {
      for (const province of regionOptions.value) {
        if (province.children) {
          for (const city of province.children) {
            if (city.value === value) {
              searchForm.province = province.label
              searchForm.city = city.label
              return
            }
          }
        }
      }
    }
  } catch (e) {
    console.error('解析搜索地区失败:', e)
  }
}

// 排序改变处理
const handleSortChange = () => {
  fetchData()
}

// 工具：格式化时间
const formatDate = (date: string | Date) => {
  if (!date) return '-'
  const d = new Date(date)
  if (isNaN(d.getTime())) return '-'
  const pad = (n: number) => n.toString().padStart(2, '0')
  const Y = d.getFullYear()
  const M = pad(d.getMonth() + 1)
  const D = pad(d.getDate())
  const h = pad(d.getHours())
  const m = pad(d.getMinutes())
  const s = pad(d.getSeconds())
  return `${Y}-${M}-${D} ${h}:${m}:${s}`
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: '',
    province: '',
    city: '',
    category: '',
    regionCascader: []
  })
  handleSearch()
}

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const editingOrganizationId = ref<string>('')
const organizationFormRef = ref()

// 机构表单数据
const organizationForm = reactive({
  name: '',
  logo: '',
  rating: 5.0,
  location: '',
  city: '',
  province: '',
  tag: '',
  category: '',
  status: 'inactive',
  regionCascader: [] as string[]
})

// 新增机构
const handleAdd = () => {
  isEdit.value = false
  resetOrganizationForm()
  dialogVisible.value = true
}

// 编辑机构
const handleEdit = (row: Organization) => {
  isEdit.value = true
  editingOrganizationId.value = row.id  // 不需要toString()，因为id已经是string类型
  fillOrganizationForm(row)
  dialogVisible.value = true
}

// 处理表格选择变化
const handleSelectionChange = (selection: Organization[]) => {
  selectedRows.value = selection
}

// 删除机构
const handleDelete = async (row: Organization) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除机构 "${row.name}" 吗？此操作不可撤销！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    const response = await request.delete(`/pcorganization/hospitals/${row.id}`) as any
    
    if (response.success) {
      ElMessage.success('删除成功')
      // 重新加载数据
      await fetchData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error: any) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      console.error('删除机构失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

// 批量启用机构
const handleBatchEnable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要启用的机构')
    return
  }

  try {
    const organizationNames = selectedRows.value.map(row => row.name).join('、')
    const confirmMessage = selectedRows.value.length === 1 
      ? `确定要启用机构 "${organizationNames}" 吗？`
      : `确定要启用选中的 ${selectedRows.value.length} 个机构吗？\n\n机构列表：${organizationNames}`

    await ElMessageBox.confirm(
      confirmMessage,
      '确认批量启用',
      {
        confirmButtonText: '确定启用',
        cancelButtonText: '取消',
        type: 'info',
        dangerouslyUseHTMLString: false
      }
    )
    
    const ids = selectedRows.value.map(row => row.id)
    console.log('=== 批量启用调试信息 ===')
    console.log('选中的行数据:', selectedRows.value)
    console.log('提取的ID列表:', ids)
    console.log('ID类型检查:', ids.map(id => ({ id, type: typeof id, length: id?.length })))
    console.log('请求数据:', { ids, status: 'active' })
    
    const response = await request.put('/pcorganization/hospitals/batch-status', {
      ids,
      status: 'active'
    }) as any
    
    if (response.success) {
      ElMessage.success(`成功启用 ${response.updatedCount} 个机构`)
      // 清空选择
      selectedRows.value = []
      // 重新加载数据
      await fetchData()
    } else {
      ElMessage.error(response.message || '批量启用失败')
    }
  } catch (error: any) {
    if (error === 'cancel') {
      ElMessage.info('已取消启用')
    } else {
      console.error('批量启用机构失败:', error)
      ElMessage.error(error.response?.data?.message || '批量启用失败')
    }
  }
}

// 批量禁用机构
const handleBatchDisable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要禁用的机构')
    return
  }

  try {
    const organizationNames = selectedRows.value.map(row => row.name).join('、')
    const confirmMessage = selectedRows.value.length === 1 
      ? `确定要禁用机构 "${organizationNames}" 吗？`
      : `确定要禁用选中的 ${selectedRows.value.length} 个机构吗？\n\n机构列表：${organizationNames}`

    await ElMessageBox.confirm(
      confirmMessage,
      '确认批量禁用',
      {
        confirmButtonText: '确定禁用',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    const ids = selectedRows.value.map(row => row.id)
    console.log('=== 批量禁用调试信息 ===')
    console.log('选中的行数据:', selectedRows.value)
    console.log('提取的ID列表:', ids)
    console.log('ID类型检查:', ids.map(id => ({ id, type: typeof id, length: id?.length })))
    console.log('请求数据:', { ids, status: 'inactive' })
    
    const response = await request.put('/pcorganization/hospitals/batch-status', {
      ids,
      status: 'inactive'
    }) as any
    
    if (response.success) {
      ElMessage.success(`成功禁用 ${response.updatedCount} 个机构`)
      // 清空选择
      selectedRows.value = []
      // 重新加载数据
      await fetchData()
    } else {
      ElMessage.error(response.message || '批量禁用失败')
    }
  } catch (error: any) {
    if (error === 'cancel') {
      ElMessage.info('已取消禁用')
    } else {
      console.error('=== 批量禁用错误详情 ===')
      console.error('完整错误对象:', error)
      console.error('错误消息:', error.message)
      console.error('响应状态:', error.response?.status)
      console.error('响应数据:', error.response?.data)
      console.error('响应头:', error.response?.headers)
      console.error('请求配置:', error.config)
      ElMessage.error(error.response?.data?.message || '批量禁用失败')
    }
  }
}

// 批量删除机构
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的机构')
    return
  }

  try {
    const organizationNames = selectedRows.value.map(row => row.name).join('、')
    const confirmMessage = selectedRows.value.length === 1 
      ? `确定要删除机构 "${organizationNames}" 吗？此操作不可撤销！`
      : `确定要删除选中的 ${selectedRows.value.length} 个机构吗？此操作不可撤销！\n\n机构列表：${organizationNames}`

    await ElMessageBox.confirm(
      confirmMessage,
      '确认批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    const ids = selectedRows.value.map(row => row.id)
    const response = await request.delete('/pcorganization/hospitals/batch', {
      data: { ids }
    }) as any
    
    if (response.success) {
      ElMessage.success(`成功删除 ${response.deletedCount} 个机构`)
      // 清空选择
      selectedRows.value = []
      // 重新加载数据
      await fetchData()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error: any) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      console.error('批量删除机构失败:', error)
      ElMessage.error(error.response?.data?.message || '批量删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchData()
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const params: any = {
      page: pagination.currentPage,
      limit: pagination.pageSize,
      sortBy: sortConfig.field,
      sortOrder: sortConfig.order
    }
    
    // 添加搜索条件
    if (searchForm.name.trim()) params.name = searchForm.name.trim()
    if (searchForm.status) params.status = searchForm.status
    if (searchForm.province) params.province = searchForm.province
    if (searchForm.city) params.city = searchForm.city
    if (searchForm.category) params.category = searchForm.category

    const res: any = await request.get('/pcorganization/hospitals', { params })
    if (res.success) {
      tableData.value = res.data
      pagination.total = res.pagination?.total || 0
    } else {
      ElMessage.error(res.message || '获取机构数据失败')
    }
  } catch (error) {
    console.error('获取机构数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 级联选择器配置
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: true, // 允许选择任意一级
  emitPath: true // 返回完整路径数组
}

// 使用npm包的省市数据
const regionOptions = ref(provinceAndCityData)


// 机构分类选项
const categoryOptions = ['民营', '公立']

// 表单验证规则
const organizationRules = {
  name: [
    { required: true, message: '请输入机构名称', trigger: 'blur' },
    { min: 2, max: 50, message: '机构名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择机构分类', trigger: 'change' }
  ],
  regionCascader: [
    { 
      required: true, 
      message: '请选择省市区域', 
      trigger: 'change',
      validator: (_rule: any, value: any, callback: any) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择省市区域'))
        } else {
          callback()
        }
      }
    }
  ],
  location: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 2, max: 200, message: '地址长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  logo: [
    { 
      required: true, 
      message: '请上传机构Logo', 
      trigger: 'change',
      validator: (_rule: any, value: any, callback: any) => {
        if (!value || value.trim() === '') {
          callback(new Error('请上传机构Logo'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 表单处理方法
const resetOrganizationForm = () => {
  Object.assign(organizationForm, {
    name: '',
    logo: '',
    rating: 5.0,
    location: '',
    city: '',
    province: '',
    tag: '',
    category: '',
    status: 'inactive',
    regionCascader: []
  })
  // 清空图片列表
  logoFileList.value = []
  // 重置编辑状态
  editingOrganizationId.value = ''
  isEdit.value = false
}

const fillOrganizationForm = (organization: Organization) => {
  Object.assign(organizationForm, {
    name: organization.name || '',
    logo: organization.image || '',
    rating: organization.rating || 5.0,
    location: organization.location || organization.address || '',
    city: organization.city || '',
    province: organization.province || '',
    tag: organization.tag || '',
    category: organization.category || '',
    status: organization.status || 'inactive',
    regionCascader: []
  })
  
  // 处理Logo图片回显
  if (organization.image) {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'
    const fullUrl = organization.image.startsWith('http') ? organization.image : `${baseURL}${organization.image}`
    
    logoFileList.value = [{
      name: 'organization-logo',
      url: fullUrl,
      uid: Date.now()
    }]
  } else {
    logoFileList.value = []
  }
  
  // 处理省市区域的回显
  if (organization.province && organization.city) {
    let foundMatch = false
    
    // 智能匹配省份 - 去除"省"、"市"等后缀进行匹配
    const normalizeProvinceName = (name: string) => {
      return name.replace(/[省市自治区特别行政区]/g, '')
    }
    
    const normalizedOrgProvince = normalizeProvinceName(organization.province)
    
    for (const province of regionOptions.value) {
      const normalizedProvince = normalizeProvinceName(province.label)
      
      // 省份匹配逻辑：完全匹配或标准化后匹配
      if (province.label === organization.province || 
          normalizedProvince === normalizedOrgProvince ||
          province.label.includes(normalizedOrgProvince) ||
          normalizedOrgProvince.includes(normalizedProvince)) {
        
        if (province.children) {
          for (const city of province.children) {
            // 城市匹配逻辑：完全匹配或包含匹配
            if (city.label === organization.city || 
                city.label.includes(organization.city.replace(/[市区县]/g, '')) ||
                organization.city.includes(city.label.replace(/[市区县]/g, ''))) {
              
              // 设置完整路径 [省份值, 城市值]
              organizationForm.regionCascader = [province.value, city.value]
              foundMatch = true
              break
            }
          }
        }
        
        if (foundMatch) break
      }
    }
  }
}

const handleDialogClose = () => {
  organizationFormRef.value?.resetFields()
  resetOrganizationForm()
  dialogVisible.value = false
}

const handleRegionChange = (value: string | string[]) => {
  if (!value || (Array.isArray(value) && value.length === 0)) {
    organizationForm.city = ''
    organizationForm.province = ''
    return
  }

  try {
    // 处理数组格式的值（完整路径）
    if (Array.isArray(value) && value.length >= 2) {
      const [provinceValue, cityValue] = value
      
      // 根据省份和城市代码找到对应的名称
      for (const province of regionOptions.value) {
        if (province.value === provinceValue && province.children) {
          organizationForm.province = province.label
          for (const city of province.children) {
            if (city.value === cityValue) {
              organizationForm.city = city.label
              return
            }
          }
        }
      }
    }
    // 处理单个值格式（向后兼容）
    else if (typeof value === 'string') {
      for (const province of regionOptions.value) {
        if (province.children) {
          for (const city of province.children) {
            if (city.value === value) {
              organizationForm.province = province.label
              organizationForm.city = city.label
              return
            }
          }
        }
      }
    }
  } catch (e) {
    console.error('解析地区失败:', e)
  }
}

const handleSubmit = async () => {
  try {
    await organizationFormRef.value?.validate()
    submitLoading.value = true
    
    const submitData = {
      name: organizationForm.name,
      logo: organizationForm.logo || undefined,
      rating: organizationForm.rating,
      location: organizationForm.location,
      city: organizationForm.city,
      province: organizationForm.province,
      tag: organizationForm.tag,
      category: organizationForm.category,
      status: organizationForm.status,
      service: [], // 初始化为空数组
      review: [],  // 初始化为空数组
      doctor: [],  // 初始化为空数组
      viewCount: 0
    }
    
    if (isEdit.value) {
      // 调用更新接口
      const response = await request.put(`/pcorganization/hospitals/${editingOrganizationId.value}`, submitData) as any
      if (response.success) {
        ElMessage.success('机构更新成功')
        fetchData() // 刷新数据
        dialogVisible.value = false // 关闭弹窗
        resetOrganizationForm() // 重置表单
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } else {
      // 调用创建接口
      const response = await request.post('/pcorganization/hospitals', submitData) as any
      if (response.success) {
        ElMessage.success('机构创建成功')
        fetchData() // 刷新数据
      } else {
        ElMessage.error(response.message || '创建失败')
      }
    }
    
    handleDialogClose()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 上传相关
const uploadHeaders = {}
const logoFileList = ref<any[]>([])


const handleUploadRemove = () => {
  organizationForm.logo = ''
  logoFileList.value = []
  // 触发表单验证
  organizationFormRef.value?.validateField('logo')
}

// 文件超出限制时的处理
const handleUploadExceed = () => {
  ElMessage.warning('只能上传一张机构Logo图片，请先删除现有图片再上传新图片')
}

// 上传前的验证
const beforeUpload = (file: any) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }

  // 检查文件大小 (2MB)
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB！')
    return false
  }

  // 如果已经有图片，先删除旧图片
  if (logoFileList.value.length > 0) {
    ElMessage.warning('只能上传一张Logo，将替换当前图片')
    organizationForm.logo = ''
    logoFileList.value = []
  }

  return true
}

// 图片预览
const previewDialogVisible = ref(false)
const previewImageUrl = ref('')

const handlePreview = (file: any) => {
  previewImageUrl.value = file.url
  previewDialogVisible.value = true
}

// 自定义上传，拼接后端完整地址（适配不同端口/代理）
const uploadRequest = async (options: any) => {
  console.log('=== uploadRequest 开始 ===')
  console.log('上传选项:', options)
  
  try {
    const form = new FormData()
    form.append('file', options.file as File)
    
    console.log('发送上传请求...')
    const res: any = await request.post('/pcproductimg/upload', form, {
      headers: { 'Content-Type': 'multipart/form-data', ...(uploadHeaders as any) },
    })
    
    console.log('上传响应:', res)
    
    if (res && res.success && res.data?.url) {
      console.log('上传成功，直接处理成功逻辑')
      
      // 保存相对路径给后端
      organizationForm.logo = res.data.url
      
      // 为 el-upload 创建完整URL用于显示缩略图
      const relativeUrl = res.data.url
      const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'
      const fullUrl = relativeUrl.startsWith('http') ? relativeUrl : `${baseURL}${relativeUrl}`
      
      const fileItem = { 
        name: res.data.filename || 'logo', 
        url: fullUrl, // 使用完整URL显示缩略图
        uid: Date.now(), // Element Plus 需要 uid
        status: 'success' // 确保状态为成功
      }
      
      // 确保只保留一张图片
      logoFileList.value = [fileItem]
      
      console.log('显示成功消息')
      ElMessage.success('机构Logo上传成功')
      
      // 触发表单验证
      organizationFormRef.value?.validateField('logo')
      
      // 通知Element Plus上传成功
      options.onSuccess?.(res)
    } else {
      console.log('上传失败，直接处理失败逻辑')
      ElMessage.error('机构Logo上传失败')
      
      const errorMsg = res?.message || '上传失败'
      options.onError?.(new Error(errorMsg))
    }
  } catch (e: any) {
    console.log('上传异常，直接处理异常逻辑:', e)
    ElMessage.error('图片上传失败')
    options.onError?.(e)
  }
}

// 生命周期
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.organization-container {
  height: calc(100vh - 60px - 48px);
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow: hidden;
}

.page-header {
  flex-shrink: 0;
  margin-bottom: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
}

.page-description {
  color: #606266;
  margin: 0;
}

.content-area {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.search-section {
  flex-shrink: 0;
  margin-bottom: 16px;
  padding: 16px;
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

.action-section {
  flex-shrink: 0;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  align-items: center;
}

.action-right {
  display: flex;
  align-items: center;
}

.table-section {
  flex: 1;
  margin-bottom: 16px;
  overflow: hidden;
}

.table-section :deep(.el-table) {
  height: 100%;
}

.table-section :deep(.el-table__body-wrapper) {
  max-height: calc(100% - 40px);
  overflow-y: auto;
}

.pagination-section {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
}

/* 已上传Logo的样式 */
.uploaded-logo-container {
  display: inline-block;
}

.logo-preview {
  position: relative;
  width: 148px;
  height: 148px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
  background-color: #fafafa;
}

.logo-image {
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #999;
  font-size: 12px;
}

.logo-actions {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 8px;
  border-radius: 4px;
}

.logo-preview:hover .logo-actions {
  opacity: 1;
}
</style>
